package zoo.member.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import zoo.member.dao.MemberDao;
import zoo.member.domain.MemberCommand;
import zoo.member.validator.MemberLoginCommandValidator;

@Controller
@RequestMapping("/main/memberlogin.do")
public class MemberLoginController {
	private static Log log = LogFactory.getLog(MemberLoginController.class);
	
	@Autowired
	private MemberDao memberDao;
	
	@ModelAttribute("memberlogin")
	public MemberCommand formBacking(){
		return new MemberCommand();
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String form(){
		return "loginPage";
	}
	
	@RequestMapping(method= RequestMethod.POST)
	public String submit(@ModelAttribute("memberlogin")MemberCommand memberCommand,
						 BindingResult result, HttpServletRequest request){
		
		new MemberLoginCommandValidator().validate(memberCommand, result);
		
		if(result.hasErrors()){
			return "loginPage";
		}
		if(log.isDebugEnabled()){
			log.debug("id : " + memberCommand.getUserid() + ", passwd : " + memberCommand.getUpwd());
		}
		
		MemberCommand command = memberDao.getMember(memberCommand.getUserid());
		
		if(command != null && memberCommand.getUpwd().equals(command.getUpwd())){
			
			//세션에 아이디를 저장
			HttpSession session = request.getSession();
			session.setAttribute("userid", memberCommand.getUserid());
			
			return "redirect:/main/index.do";
			
		}else{
			//아이디 또는 비밀번호가 일치 하지 않음
			result.reject("invalidIdOrPassword.command", new Object[]{memberCommand.getUserid()},null);
			
			return "loginPage";
		}
	}
}
